<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>霸屏系统LED客户端</title>
</head>
<body>
<hr/>
<div id="message" style="overflow:auto;height: 300px;color: #0F0;background-color: #000;"></div>
<hr/><!--
<input id="name" type="text" value="#(name??'王晓丽')"/>
<button onclick="setName()">昵称</button>
<hr/>
<textarea id="text" rows="5" cols="">大家好~我是#(name??'王晓丽')！</textarea>
<button onclick="send()">发送</button>
<hr/>
<button onclick="setName()" type="button">上线</button>
<button onclick="closeWebSocket()" type="button">下线</button>-->
</body>

<script src="https://libs.baidu.com/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
    var websocket = null;
    setName("相约久久酒吧b");

    function setName(name) {
        var name = name;
        var host = window.location.host;//+window.location.pathname;
        console.log(new Date(), name, " 上线");
        $.getJSON("/led/interact/getwebsocket_led", {"name": name, "host": host}, function (ret) {
            if (ret.state == "ok") {
                newWebSocket(ret.url);
            } else {
                alert('抱歉，失败')
            }
        });
    }

    function newWebSocket(url) {
        if ('WebSocket' in window) {
            websocket = new WebSocket(url);
        } else {
            alert('请使用火狐或谷歌浏览器等兼容websocket的浏览器!')
            return;
        }
        //连接发生错误的回调方法
        websocket.onerror = function () {
            setMessageInnerHTML("离线");
        }

        //连接成功建立的回调方法
        websocket.onopen = function () {
            setMessageInnerHTML("LED上线");
        }

        //接收到消息的回调方法
        websocket.onmessage = function (event) {
            setMessageInnerHTML(event.data);
        }

        //连接关闭的回调方法
        websocket.onclose = function () {
            setMessageInnerHTML("下线");
        }

    }

    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML) {
        var e = document.getElementById('message');
        e.innerHTML += innerHTML + '<br/><br/>';
        e.scrollTop = e.scrollHeight;
    }

    //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function () {
        closeWebSocket();
    }

    //关闭WebSocket连接
    function closeWebSocket() {
        if (websocket != null) {
            websocket.close();
        }
    }

    //发送消息
    function send() {
        if (websocket == null) {
            setName();
            return;
        }
        var message = document.getElementById('text').value;
        websocket.send(message);
    }

</script>
</html>